package services

import (
	"fmt"
	"time"
)

type PowerData struct {
	Timestamp time.Time
	PowerKW   float64
}

type PriceData struct {
	Timestamp time.Time
	Price     float64
}

type StorageStrategy struct {
	Timestamp time.Time
	Action    string  // "charge", "discharge", or "idle"
	PowerKW   float64 // positive for charge, negative for discharge
}

type PowerAnalysis struct {
	MaxDemandKW    float64 // 最大需量
	AvgPowerKW     float64 // 平均功率
	TotalEnergyKWh float64 // 总用电量
}

func AnalyzePowerData(powerData []PowerData) PowerAnalysis {
	var (
		maxDemand   float64
		totalEnergy float64
	)

	for _, data := range powerData {
		if data.PowerKW > maxDemand {
			maxDemand = data.PowerKW
		}
		totalEnergy += data.PowerKW // 假设数据是每小时一个点
	}

	return PowerAnalysis{
		MaxDemandKW:    maxDemand,
		AvgPowerKW:     totalEnergy / float64(len(powerData)),
		TotalEnergyKWh: totalEnergy,
	}
}

func CalculateStorageCapacity(analysis PowerAnalysis, priceData []PriceData) float64 {
	// 简单策略：根据最大需量和平均功率计算储能容量
	// 这里可以根据具体需求调整计算公式
	capacity := analysis.MaxDemandKW * 2 // 假设储能容量是最大需量的2倍
	return capacity
}

func CalculateStorageStrategy(powerData []PowerData, priceData []PriceData) ([]StorageStrategy, error) {
	if len(powerData) != 24 || len(priceData) != 24 {
		return nil, fmt.Errorf("需要24小时的数据")
	}

	strategies := make([]StorageStrategy, 0, 24)

	for i := 0; i < 24; i++ {
		strategy := StorageStrategy{
			Timestamp: powerData[i].Timestamp,
		}

		// 简单策略：电价低时充电，电价高时放电
		if priceData[i].Price < 0.3 { // 假设0.3是低价阈值
			strategy.Action = "charge"
			strategy.PowerKW = min(100, powerData[i].PowerKW) // 假设最大充电功率100kW
		} else if priceData[i].Price > 0.5 { // 假设0.5是高价阈值
			strategy.Action = "discharge"
			strategy.PowerKW = -min(100, powerData[i].PowerKW) // 假设最大放电功率100kW
		} else {
			strategy.Action = "idle"
			strategy.PowerKW = 0
		}

		strategies = append(strategies, strategy)
	}

	return strategies, nil
}

func min(a, b float64) float64 {
	if a < b {
		return a
	}
	return b
}
